//
//  XCSearchBarViewController.m
//  SoundOfNature
//
//  Created by 梁新昌 on 16/3/13.
//  Copyright © 2016年 梁新昌. All rights reserved.
//

#import "XCSearchBarViewController.h"
#import "XCAFNetTool.h"
#import "XCUrlManger.h"
#import "XCSearchBarViewController.h"
#import "XCShareMusicTableViewCell.h"
#import "MJRefresh.h"
#import "OnlineAVplay.h"
#import "XCPlayViewController.h"
@interface XCSearchBarViewController ()<UISearchBarDelegate, UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, retain) UISearchBar *searchBar;
@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, retain) NSMutableArray *dataSource;
@property (nonatomic, assign) NSUInteger page;
@property (nonatomic, retain) NSArray *myArray;

@property (nonatomic, retain) NSMutableArray *mutableArraySongName;

@property (nonatomic, retain) NSMutableArray *mutableArraySingerNAme;

@property (nonatomic, retain) NSMutableArray *nameArray;

@property (nonatomic, retain) NSMutableArray *mutableHeadIVPicurl;

@end

@implementation XCSearchBarViewController

- (void)dealloc {
    
    _searchBar.delegate = nil;
    _tableView.dataSource = nil;
    _tableView.delegate = nil;
    
    [_searchBar release];
    [_tableView release];
    [_myArray release];
    [_dataSource release];
    [_mutableHeadIVPicurl release];
    [_nameArray release];
    [_mutableArraySongName release];
    [_mutableArraySingerNAme release];
    
    [super dealloc];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:NO];
    [self readNSUserDefaults];
//    self.navigationController.navigationBar.hidden = YES;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"搜索";

    self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, wide, 40)];
    self.searchBar.delegate = self;
    _searchBar.barStyle = UIBarStyleBlackOpaque;
    _searchBar.placeholder = @"Please Enter search";
    _searchBar.keyboardType = UIReturnKeyDefault;
    
    [_searchBar setShowsCancelButton:YES];
    [_searchBar setShowsSearchResultsButton:YES];
    self.dataSource = [NSMutableArray arrayWithCapacity:0];
    
    self.mutableArraySongName = [NSMutableArray arrayWithCapacity:0];
    self.mutableHeadIVPicurl = [NSMutableArray arrayWithCapacity:0];
    self.mutableArraySingerNAme = [NSMutableArray arrayWithCapacity:0];
    self.nameArray = [NSMutableArray arrayWithCapacity:0];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"Image-leftBarButton"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(leftBarButtonItemAction)];
    self.page = 1;
    [self tableViewBuildAction];
    [self.view addSubview:_searchBar];
    [_searchBar release];
}
// 点击取消时候执行下面的方法
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    [self.searchBar resignFirstResponder];
    [self.searchBar setShowsCancelButton:NO animated:YES];
//    [liveViewAreaTable searchDataBySearchString:nil];// 搜索tableView数据
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    [self.tableView removeFromSuperview];
//    [self controlAccessoryView:0];// 隐藏遮盖层。
//    [self.dataSource removeAllObjects];
}
// 点击搜索执行的方法
// 键盘中，搜索按钮被按下，执行的方法
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    [self.dataSource removeAllObjects];
    [self.searchBar resignFirstResponder];// 放弃第一响应者
//    [liveViewAreaTable searchDataBySearchString:searchBar.text];
//    [self.navigationController setNavigationBarHidden:NO animated:YES];
//    [self controlAccessoryView:0];// 隐藏遮盖层。
    if (self.searchBar.text.length > 0) {
        
        [self searchBarText:self.searchBar.text];//缓存搜索记录
        [self readNSUserDefaults];
        
    }else{
        NSLog(@"请输入查找内容");
    }
    [self searchNetRequest];
    
    [self.tableView addFooterWithTarget:self action:@selector(searchNetRequest)];
    [self.tableView footerBeginRefreshing];
    


}
- (void)searchNetRequest {
    
    [XCAFNetTool GETNetWithUrl:[XCUrlManger searchNetRequest:self.searchBar.text withPage:self.page] body:nil headerFile:nil response:XCJSON success:^(id result) {
        
        NSArray *array = [NSArray arrayWithArray:result[@"data"]];
        if (array.count != 0) {
            for (NSDictionary *dic in result[@"data"]) {
                
                XCSearchModel *searchModel = [[XCSearchModel alloc] initWithDataSource:dic];
                if (searchModel.picUrl != nil && searchModel.urlList.count != 0 && searchModel.name !=nil && searchModel.singerName != nil) {
                    [self.dataSource addObject:searchModel];
                }
                [searchModel release];
            }
            
            [self.tableView reloadData];
            [self.tableView footerEndRefreshing];
            self.page++;
        } else {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"没有相关资源" message:@"本宝宝正在为您努力加载" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *sure = [UIAlertAction actionWithTitle:@"加油" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            }];
            [alert addAction:sure];
            
            [self presentViewController:alert animated:YES completion:^{
                
            }];

        }
        
    } failure:^(NSError *error) {


    }];
}
- (void)tableViewBuildAction {
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, wide, high - 40) style:UITableViewStyleGrouped];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.backgroundColor = [UIColor clearColor];
    [self.tableView registerClass:[XCShareMusicTableViewCell class] forCellReuseIdentifier:@"XCShareMusicTableViewCell"];
    self.view.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.tableView];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_tableView release];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        if (_myArray.count > 0) {
            return _myArray.count+2;
        }else {
            return 1;
        }
    } else {
        return self.dataSource.count;
    }
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==0) {
        if(indexPath.row ==0){
            UITableViewCell * cell = [[UITableViewCell alloc] initWithStyle:0 reuseIdentifier:@"cell"];
            cell.textLabel.text = @"历史搜索";
            
            return cell;
        }else if (indexPath.row == _myArray.count+1){
            UITableViewCell * cell = [[UITableViewCell alloc] initWithStyle:0 reuseIdentifier:@"cell"];
            cell.textLabel.text = @"清除历史记录";
    
            cell.textLabel.textAlignment = NSTextAlignmentCenter;
            return cell;
        }else{
            UITableViewCell * cell = [[UITableViewCell alloc] initWithStyle:0 reuseIdentifier:@"cell"];
            NSArray* reversedArray = [[_myArray reverseObjectEnumerator] allObjects];
            cell.textLabel.text = reversedArray[indexPath.row-1];
            return cell;
        }
    }else{
        XCShareMusicTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"XCShareMusicTableViewCell"];
        XCSearchModel *searchModel = self.dataSource[indexPath.row];
        cell.searchModel = searchModel;
        cell.numberLable.text = [NSString stringWithFormat:@"%ld", indexPath .row + 1];
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0) {
        if (indexPath.row == _myArray.count + 1) {//清除所有历史记录
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"清除历史记录" message:@"" preferredStyle: UIAlertControllerStyleAlert];
            
            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
            UIAlertAction *deleteAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
                [self removeAllArray];
                _myArray = nil;
                [self.tableView reloadData];
                
            }];
            
            [alertController addAction:cancelAction];
            [alertController addAction:deleteAction];
            
            [self presentViewController:alertController animated:YES completion:nil];
            
        }else {
            NSArray *array = [[_myArray reverseObjectEnumerator] allObjects];
            _searchBar.text = array[indexPath.row - 1];
            [_tableView reloadData];
        }
        
    } else if (indexPath.section == 1) {
        
        XCSearchModel *searchModel = self.dataSource[indexPath.row];
        for (XCInTheSongListModel *inTheSongListModel in self.dataSource) {
            if (inTheSongListModel.urlList.count != 0 && inTheSongListModel.urlList != nil && inTheSongListModel.picUrl != nil && inTheSongListModel.singerName != nil) {
                [self.mutableHeadIVPicurl addObject:inTheSongListModel.picUrl];
                [self.mutableArraySingerNAme addObject:inTheSongListModel.singerName];
                [self.nameArray addObject:inTheSongListModel.name];
                [self.mutableArraySongName addObject:[inTheSongListModel.urlList[0] objectForKey:@"url"]];
            }
        }
        [XCPlayViewController sharePlayViewController].muatbleArraySingerName = self.mutableArraySingerNAme;
        [XCPlayViewController sharePlayViewController].mutableArraySongName = self.mutableArraySongName;
        [XCPlayViewController sharePlayViewController].mutableHeadIVPicurl = self.mutableHeadIVPicurl;
        [XCPlayViewController sharePlayViewController].selectIndex = indexPath.row;
        [XCPlayViewController sharePlayViewController].nameArray = self.nameArray;
        
        [[OnlineAVplay shareAVPlayer] playWithUrl:[searchModel.urlList[0] objectForKey:@"url"]];
        [[OnlineAVplay shareAVPlayer] play];
        [OnlineAVplay shareAVPlayer].isPlay = YES;
        
        [self presentViewController:[XCPlayViewController sharePlayViewController] animated:YES completion:^{
            
        }];
    }
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return wide / 7;
    } else {
        return wide / 5;
    }
    
}


#pragma mark - 存到本地
- (void)searchBarText:(NSString *)searchBarText {
    NSUserDefaults *userDefaultes = [NSUserDefaults standardUserDefaults];
//    读取本地 数组 nsarray类型的数据
    NSArray *myArray = [userDefaultes arrayForKey:@"myArray"];
//    先取出数组, 判断是否有值, 有值继续添加, 无值创建数组
    if (myArray.count > 0) {
        
    } else {
        myArray = [NSArray array];
    }
//    创建一个可变数组进行操作
    NSMutableArray *searTXT = [myArray mutableCopy];
    [searTXT addObject:searchBarText];
    if (searTXT.count > 3) {
        [searTXT removeObjectAtIndex:0];
    }
//    将上述数据全部存到 NSUserDefaults中
    [userDefaultes setObject:searTXT forKey:@"myArray"];
    [userDefaultes synchronize];
    NSLog(@"%ld", myArray.count);
}
// 移除本地数据
- (void)removeAllArray {
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults removeObjectForKey:@"myArray"];
    [userDefaults synchronize];
}
// 读取缓存数据
- (void)readNSUserDefaults {
    NSUserDefaults *userDefaultes = [NSUserDefaults standardUserDefaults];
//    读取 NSArray
    NSArray *myArray = [userDefaultes arrayForKey:@"myArray"];
    self.myArray = myArray;
//    [self.tableView reloadData];
    NSLog(@"myArray=====%@", myArray);
}

// 隐藏底部
//- (void)viewWillAppear:(BOOL)animated {
//
//    self.navigationController.tabBarController.tabBar.hidden = YES;
//}
//- (void)viewWillDisappear:(BOOL)animated {
//    self.navigationController.navigationBarHidden = NO;
//}

- (void)leftBarButtonItemAction {
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

@end
